﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using Components;
using System.Configuration;
using Meeting.Model;
using System.ComponentModel;
using System.Drawing.Imaging;
using Meeting.Public;
using Meeting.Office2Image;

namespace JQueryUploadDemo
{
    /// <summary>
    /// UploadHander 的摘要说明
    /// </summary>
    public class UploadHander : IHttpHandler
    {
        private string FileId = "";
        private string FilePath = "";
        public void ProcessRequest(HttpContext context)
        {

            context.Response.ContentType = "text/plain";
            string MeetingId = context.Request["MeetingId"];//原来是给会议传文档，现在思路是给议题上传文档，所以这个id作为议题id
            string TopicId = context.Request["tId"];
            string[] strs = TopicId.Split('|');
            TopicId = strs[0];
            MeetingId = strs[1];
            HttpPostedFile postedFile = context.Request.Files["Filedata"];
            string uploadPath = context.Server.MapPath("~/" + ConfigurationManager.AppSettings["UploadPath"] + "/");
            if (postedFile != null)
            {
                Guid docId = Guid.NewGuid();

                string fullName = postedFile.FileName;
                //获取文件后缀名
                string extension = fullName.Substring(fullName.LastIndexOf("."), (fullName.Length - fullName.LastIndexOf("."))).ToLower();
                //按年月生成文件夹
                string dateFolder = StrHelp.MakeFolderName();
                //拼接上传路径
                uploadPath = uploadPath + dateFolder + "/" + TopicId.ToString();
                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }
                string filePath = uploadPath + "/" + docId + extension;
                postedFile.SaveAs(filePath);
                //文件保存成功之后，将文件转换为图片
                int imageCount = 0;
                string imagePath = uploadPath + "/" + docId + "/";
                if (!Directory.Exists(imagePath))
                {
                    Directory.CreateDirectory(imagePath);
                }


                OfficeToImage.ConvertToImage(filePath, imagePath, "", out imageCount);
               
                
                //switch (extension.ToLower())
                //{
                //    case ".pdf":
                //        PDF2Image.ConvertPDF2Image(filePath, imagePath, "", 1, 100000000, ImageFormat.Jpeg, PDF2Image.Definition.Three, out imageCount);
                //        break;
                //    case ".doc":
                //    case ".docx":
                //        Meeting.Office2Image.Word2Image.ConvertWordToImage(filePath, imagePath, "", 1, 100000000, ImageFormat.Jpeg, 128, out imageCount);
                //        break;

                //} 

                //文件保存成功之后，在数据库中插入一条记录
                TopicDocument docModel = new TopicDocument();
                docModel.Comment = "";
                docModel.IsActive = true;
                docModel.Id = docId;
                docModel.Name = fullName;
                docModel.UploadDate = DateTime.Now;
                docModel.TopicId = new Guid(TopicId);
                docModel.Path = dateFolder;
                docModel.Format = extension.Replace(".", "");
                docModel.MeetingId = CommonFunction.varToIntDef(MeetingId, 0);
                docModel.ImageCount = imageCount;
                //信息写入数据库
                Meeting.BLL.TopicBLL bll = new Meeting.BLL.TopicBLL();
                context.Response.Write(bll.AddDocument(docModel,true));
                //FileDeepProcess(string.Format("{0}{1}\\{2}", uploadPath, folderName, fileName));
                //下面这句代码缺少的话，上传成功后上传队列的显示不会自动消失
                //context.Response.Write(string.Format("{0}/{1}", filePath, fullName));
            }
            else
            {
                context.Response.Write("0");
            }
        }

        private string GetMeetingIdByTopicId(string topicId)
        {
            //throw new NotImplementedException();
            Meeting.BLL.MeetingBLL meeting = new Meeting.BLL.MeetingBLL();
            return meeting.GetMeetingIdByTopicId(topicId);

        }

        //private void SaveMeetingDocumentInfo(Meeting.Model.MeetingDocument documentInfo)
        //{
        //    //throw new NotImplementedException();
        //    Meeting.BLL.MeetingFiles mf = new Meeting.BLL.MeetingFiles();
        //    mf.Add(documentInfo);
        //    FileId = mf.GetModel(documentInfo.Name).Id.ToString();
        //}

        private void FileDeepProcess(string fileName)
        {
            string extension = GetFileExtension(fileName);
            if (extension == ".bmp" || extension == ".gif" || extension == ".jpg" || extension == ".jpeg")
            {
                ImageFileProcess(fileName);
            }
            else if (extension == ".doc" || extension == ".docx")
            {
                DocFileProcess(fileName);
            }
            else if (extension == ".xlsx" || extension == ".xls")
            {
                ExcelFileProcess(fileName);

            }
            else if (extension == "pdf")
            {
                PDFFileProcess(fileName);
            }
            else if (extension == "ppt")
            { }


        }

        private void PDFFileProcess(string fileName)
        {
            // throw new NotImplementedException();
            BackgroundWorker bw = new BackgroundWorker();
            bw.DoWork += new DoWorkEventHandler(Pdf2Image);
            bw.RunWorkerAsync(fileName);
        }
        private void Pdf2Image(object sender, DoWorkEventArgs e)
        {
            string fileName = sender as string;
            string imageOutputPath = Path.GetDirectoryName(fileName) + "\\" + Path.GetFileNameWithoutExtension(fileName);
            imageOutputPath = FilePath + "\\" + FileId;
            string imageNameStart = Path.GetFileNameWithoutExtension(fileName);
            int imagecount = 0;
            PDF2Image.ConvertPDF2Image(fileName, imageOutputPath, imageNameStart, 1, 5, ImageFormat.Jpeg, PDF2Image.Definition.One, out imagecount);
        }
        private string GetFileExtension(string fileName)
        {
            //获取文件后缀名
            string extension = fileName.Substring(fileName.LastIndexOf("."), (fileName.Length - fileName.LastIndexOf("."))).ToLower();
            return extension;

        }
        private void ExcelFileProcess(string fileName)
        {
            //throw new NotImplementedException();
        }

        private void DocFileProcess(string fileName)
        {
            //throw new NotImplementedException();
            BackgroundWorker bw = new BackgroundWorker();
            bw.DoWork += new DoWorkEventHandler(Word2Image);
            bw.RunWorkerAsync(fileName);
        }
        private void Word2Image(object sender, DoWorkEventArgs e)
        {
            string fileName = sender as string;
            string imageOutputPath = Path.GetDirectoryName(fileName) + "\\" + Path.GetFileNameWithoutExtension(fileName);
            imageOutputPath = FilePath + "\\" + FileId;
            int imagecount = 0;
            Meeting.Office2Image.Word2Image.ConvertWordToImage(fileName, imageOutputPath, "", 0, 0, null, 0, out imagecount);
        }
        public void ImageFileProcess(string fileName)
        {

            //缩略图100*65
            //UploadPic.MakeThumbnail(string.Format("original\\{0}\\{1}", folderName, fileName), string.Format("100X65\\{0}\\{1}", folderName, fileName), 100, 65, "Cut");
            //缩略图550(限宽)
            //UploadPic.MakeThumbnail(string.Format("original\\{0}\\{1}", folderName, fileName), string.Format("550\\{0}\\{1}", folderName, fileName), 550, 0, "W");

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}